#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char* argv[])
{
    // if(argc < 3)
    // {
    // 	printf("./client [addr:][port:]\n");
    // 	return 4;
    // }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0) {
        perror("socket");
        return 1;
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    // server.sin_port = htons(atoi(argv[2]));
    // server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port        = htons(9966);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    printf("%d %d\n", server.sin_addr.s_addr, server.sin_port);
    char               buf[1024];
    struct sockaddr_in peer;
    socklen_t          len = sizeof(peer);
    while(1) {
        memcpy(buf, "hello", 5);
        sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&server,
            sizeof(server));
        int s = recvfrom(
            sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
        printf("%d %d\n", peer.sin_addr.s_addr, peer.sin_port);

        if(s < 0) {
            perror("recvfrom");
            return 3;
        } else if(s == 0) {
            printf("server closed\n");
        } else {
            buf[s] = 0;
            printf("#server echo#  %s\n", buf);
            if(strcmp(buf, "quit") == 0) break;
        }
        sleep(3);
    }

    return 0;
}